/**
 * @description 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */

import Vue from 'vue'
import { getUserInfo, login, logout } from '@/api/user'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
} from '@/utils/accessToken'
import { resetRouter } from '@/router'
import { title, tokenName } from '@/config'

const state = () => ({
  token: getAccessToken(),
  username: '',
  avatar: '',
  cangkuid: '',
  cangkumc: '',
  permissions: [],
  userInfo: {},
})
const getters = {
  accessToken: (state) => state.token,
  userInfo: (state) => state.userInfo,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
  permissions: (state) => state.permissions,
  cangkuid: (state) => state.cangkuid,
  cangkumc: (state) => state.cangkumc,
}
const mutations = {
  setCangkuId(state, cangkuid) {
    state.cangkuid = cangkuid
  },
  setCangkuMc(state, cangkumc) {
    state.cangkumc = cangkumc
  },
  setAccessToken(state, token) {
    state.token = token
    setAccessToken(token)
  },
  setUsername(state, username) {
    state.username = username
  },
  setAvatar(state, avatar) {
    state.avatar = avatar
  },
  setPermissions(state, permissions) {
    state.permissions = permissions
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
    localStorage.setItem("userInfo", userInfo)
  },

}
const actions = {
  setPermissions({ commit }, permissions) {
    commit('setPermissions', permissions)
  },
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo)
    const token = data.token
    if (token) {
      commit('setAccessToken', token)
      commit('setUserInfo', JSON.stringify(data.yonghu))
      const hour = new Date().getHours()
      const thisTime =
        hour < 8
          ? '早上好'
          : hour <= 11
            ? '上午好'
            : hour <= 13
              ? '中午好'
              : hour < 18
                ? '下午好'
                : '晚上好'
      Vue.prototype.$baseNotify(`欢迎登录${title}`, `${thisTime}！`)
    } else {
      Vue.prototype.$baseMessage(
        `登录接口异常，未正确返回token...`,
        'error'
      )
    }
  },
  async getUserInfo({ commit, state }) {
    const { data } = await getUserInfo()
    if (!data) {
      Vue.prototype.$baseMessage('验证失败，请重新登录...', 'error')
      return false
    }
    let cangkuid = data[0].id
    let cangkumc = data[0].text
    if (cangkuid) {
      commit('setCangkuId', cangkuid)
      commit('setCangkuMc', cangkumc)
      return cangkuid
    } else {
      Vue.prototype.$baseMessage('用户信息接口异常', 'error')
      return false
    }
    return
  },
  async logout({ dispatch }) {
    // await logout(state.token)
    await dispatch('resetAccessToken')
    await resetRouter()
  },
  resetAccessToken({ commit }) {
    commit('setPermissions', [])
    commit('setAccessToken', '')
    removeAccessToken()
  },
}
export default { state, getters, mutations, actions }
